Plotting

Reference

https://github.com/JuliaComputing/JuliaBoxTutorials/tree/master/introductory-tutorials/intro-to-julia (github : JuliaComputing/JuliaBoxTutorials/introductory-tutorials/intro-to-julia/)

Topics:

  1. Basics
  2. Exercises

Series

Basics

There are a few different ways to plot in Julia (including calling PyPlot).

Here we'll show you how to use Plots.jl. If it's not installed yet, you need to use the package manager to install it, and Julia will precompile it for you the first time you use it:

In [1]:
using Pkg
Pkg.add("Plots")
using Plots
  Updating registry at `~/.julia/registries/General`
  Updating git-repo `https://github.com/JuliaRegistries/General.git`
 Resolving package versions...
  Updating `~/.julia/environments/v1.0/Project.toml`
 [no changes]
  Updating `~/.julia/environments/v1.0/Manifest.toml`
 [no changes]

One of the advantages to Plots.jl is that it allows you to seamlessly change backends. In this notebook, we'll try out the gr() and unicodeplots() backends.

In the name of scientific inquiry, let's use this notebook to examine the relationship between the global temperature and the number of pirates between roughly 1860 and 2000.

In [2]:
globaltemperatures = [14.4, 14.5, 14.8, 15.2, 15.5, 15.8]
numpirates = [45000, 20000, 15000, 5000, 400, 17];

Plots supports multiple backends — that is, libraries that actually do the drawing — all with the same API. To start out, let's try the GR backend. You choose it with a call to gr():

In [3]:
gr()
Out[3]:
Plots.GRBackend()

and now we can use commands like plot and scatter to generate plots.

In [4]:
plot(numpirates, globaltemperatures, label="line")  
scatter!(numpirates, globaltemperatures, label="points")
Out[4]:
0 1×10 4 2×10 4 3×10 4 4×10 4 14.50 14.75 15.00 15.25 15.50 15.75 line points

The ! at the end of the scatter! function name makes scatter! a mutating function, indicating that the scattered points will be added onto the pre-existing plot.

In contrast, see what happens when you replace scatter! in the above with the non-mutating function scatter.

Next, let's update this plot with the xlabel!, ylabel!, and title! commands to add more information to our plot.

In [5]:
xlabel!("Number of Pirates [Approximate]")
ylabel!("Global Temperature (C)")
title!("Influence of pirate population on global warming")
Out[5]:
0 1×10 4 2×10 4 3×10 4 4×10 4 14.50 14.75 15.00 15.25 15.50 15.75 Influence of pirate population on global warming Number of Pirates [Approximate] Global Temperature (C) line points

This still doesn't look quite right. The number of pirates has decreased since 1860, so reading the plot from left to right is like looking backwards in time rather than forwards. Let's flip the x axis to better see how pirate populations have caused global temperatures to change over time!

In [6]:
xflip!()
Out[6]:
0 1×10 4 2×10 4 3×10 4 4×10 4 14.50 14.75 15.00 15.25 15.50 15.75 Influence of pirate population on global warming Number of Pirates [Approximate] Global Temperature (C) line points

And there we have it!

Note: We've had some confusion about this exercise. :) This is a joke about how people often conflate correlation and causation.

Without changing syntax, we can create this plot with the UnicodePlots backend

In [7]:
Pkg.add("UnicodePlots")
unicodeplots()
 Resolving package versions...
  Updating `~/.julia/environments/v1.0/Project.toml`
 [no changes]
  Updating `~/.julia/environments/v1.0/Manifest.toml`
 [no changes]
Out[7]:
Plots.UnicodePlotsBackend()
In [8]:
plot(numpirates, globaltemperatures, label="line")  
scatter!(numpirates, globaltemperatures, label="points") 
xlabel!("Number of Pirates [Approximate]")
ylabel!("Global Temperature (C)")
title!("Influence of pirate population on global warming")
Out[8]:
                                   Influence of pirate population on global warming
                             +------------------------------------------------------------+       
                          16 |          ,                                                 | line  
                             |          |                                                 | points
                             |          |                                                 |       
                             |          |                                                 |       
                             |          |                                                 |       
                             |          F.                                                |       
                             |          | \.                                              |       
                             |          |  ".                                             |       
                             |          |    "..                                          |       
   Global Temperature (C)    |          |      "`.                                        |       
                             |          |         "-.                                     |       
                             |          |           "\..                                  |       
                             |          |              \.                                 |       
                             |          |                `.                               |       
                             |          |                 ".                              |       
                             |          |                   """"""""`-------.________.    |       
                             |          |                                                 |       
                             |          |                                                 |       
                             |          |                                                 |       
                          14 |          |                                                 |       
                             +------------------------------------------------------------+       
                             -10000                                                   50000
                                            Number of Pirates [Approximate]

And notice how this second plot differs from the first! Using text like this is a little silly in a Jupyter notebook where we have fancy drawing capabilities, but it can be very useful for quick and dirty visualization in a terminal.

Note that to use plotlyjs(), you have to install the package PlotlyJS first.

In [9]:
plotlyjs()
ArgumentError: Package PlotlyJS not found in current path:
- Run `Pkg.add("PlotlyJS")` to install the PlotlyJS package.


Stacktrace:
 [1] require(::Module, ::Symbol) at ./loading.jl:817
 [2] top-level scope at /home/yt/.julia/packages/Plots/zCttE/src/backends.jl:320
 [3] eval at ./boot.jl:319 [inlined]
 [4] _initialize_backend(::Plots.PlotlyJSBackend) at /home/yt/.julia/packages/Plots/zCttE/src/backends.jl:319
 [5] backend(::Plots.PlotlyJSBackend) at /home/yt/.julia/packages/Plots/zCttE/src/backends.jl:196
 [6] backend(::Symbol) at /home/yt/.julia/packages/Plots/zCttE/src/backends.jl:209
 [7] plotlyjs() at /home/yt/.julia/packages/Plots/zCttE/src/backends.jl:29
 [8] top-level scope at In[9]:1

Exercises

8.1

Given

x = -10:10

plot y vs. x for $y = x^2$. You may want to change backends back again.

In [10]:
x = -10:10
unicodeplots()
plot(x, x.^2, label="line")  
scatter!(x, x.^2, label="points")
Out[10]:
        +------------------------------------------------------------+       
    200 |                              ,                             | line  
        |                              |                             | points
        |                              |                             |       
        |                              |                             |       
        |                              |                             |       
        |                              |                             |       
        |               .              |             ..              |       
        |               ".             |            ./               |       
        |                ".            |           /`                |       
        |                  \.          |         ./                  |       
        |                   '.         |        ./                   |       
        |                     "\.      |      ./                     |       
        |                       '`..   |  ../"                       |       
        |--------------------------fPPPPPP--------------------------*|       
        |                              |                             |       
        |                              |                             |       
        |                              |                             |       
        |                              |                             |       
        |                              |                             |       
   -100 |                              |                             |       
        +------------------------------------------------------------+       
        -20                                                         20
In [11]:
gr()
plot(x, x.^2, label="line")  
scatter!(x, x.^2, label="points")
Out[11]:
-10 -5 0 5 10 0 25 50 75 100 line points

8.2

Execute the following code

In [12]:
p1 = plot(x, x)
p2 = plot(x, x.^2)
p3 = plot(x, x.^3)
p4 = plot(x, x.^4)
plot(p1, p2, p3, p4, layout = (2, 2), legend = false)
Out[12]:
-10 -5 0 5 10 -10 -5 0 5 10 -10 -5 0 5 10 0 25 50 75 100 -10 -5 0 5 10 -1000 -500 0 500 1000 -10 -5 0 5 10 0 2500 5000 7500 10000

and then create a $4x1$ plot that uses p1, p2, p3, and p4 as subplots.

In [13]:
plot(p1, p2, p3, p4, layout = (4, 1), legend = false)
Out[13]:
-10 -5 0 5 10 -10 -5 0 5 10 -10 -5 0 5 10 0 25 50 75 100 -10 -5 0 5 10 -1000 -500 0 500 1000 -10 -5 0 5 10 0 2500 5000 7500 10000